import time
from src.utils.logger import get_logger
import pyJianYingDraft as draft
from src.utils.redis import RedisHelper
from typing import Optional
logger = get_logger("capcut")

# 缓存配置常量
CACHE_KEY_PREFIX = "script_draft_cache:"  # 缓存键前缀，避免命名冲突
LRU_ZSET_KEY = "script_draft_cache_lru"   # 存储LRU顺序的ZSET键名
MAX_CACHE_SIZE = 10000             # 最大缓存数量，保持原配置


def update_cache_redis(key: str, value: draft.Script_file) -> None:
    """使用Redis更新缓存，保持LRU淘汰策略"""
    redis_key = f"{CACHE_KEY_PREFIX}{key}"
    try:
        # 1. 如果键已存在，先删除旧缓存和LRU记录
        if RedisHelper.exists(redis_key):
            RedisHelper.delete(redis_key)
            RedisHelper.zrem(LRU_ZSET_KEY, redis_key)
            logger.info(f"Removed existing cache entry: {redis_key}")
        # 2. 检查缓存是否已满
        current_size = RedisHelper.zcard(LRU_ZSET_KEY)
        if current_size >= MAX_CACHE_SIZE:
            # 获取最久未使用的键（最小时间戳）
            oldest_keys = RedisHelper.zrange(LRU_ZSET_KEY, 0, 0)
            if oldest_keys:
                oldest_key = oldest_keys[0]
                # 删除最久未使用的缓存项和LRU记录
                RedisHelper.delete(oldest_key)
                RedisHelper.zrem(LRU_ZSET_KEY, oldest_key)
                logger.info(f"Cache is full, evicted LRU key: {oldest_key}")
        # 3. 添加新缓存项到Redis
        RedisHelper.set(redis_key, value)
        # 4. 更新LRU ZSET（当前时间戳作为score）
        current_timestamp = time.time()
        RedisHelper.zadd(LRU_ZSET_KEY, {redis_key: current_timestamp})
        logger.info(f"Successfully updated cache for key: {key}")
    except Exception as e:
        logger.error(f"Failed to update cache for key {key}: {str(e)}")

def get_cache(key: str) -> Optional[draft.Script_file]:
    """从Redis获取缓存数据"""
    redis_key = f"{CACHE_KEY_PREFIX}{key}"
    return RedisHelper.get(redis_key)